package com.project.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;
import com.project.bean.ValidateAdd;
import com.project.bean.ValidateUpdate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLDecoder;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping("upload")
    public  String add(String userName,
          @RequestParam("face")MultipartFile mf) throws Exception{
        //得到上传文件名称
        String fileName = mf.getOriginalFilename();
        //得到上传文件存放目录的真实路径
        URL url = Thread.currentThread().getContextClassLoader()
                .getResources("static/html/img").nextElement();
        String filePath = URLDecoder.decode(url.getFile(),"utf-8");

        //将上传文件保存到指定目录
        mf.transferTo(new File(filePath+"/"+fileName));
        System.out.println("userName = "+userName);
        return "ok";
    }

    //@Valid当前提交需要使用实体类中定义的注解验证。
    //如果有验证失败信息，则存放在BindResult对象中
    @RequestMapping("register")
    public String register(
            @Validated(ValidateAdd.class) UserBean user,
            BindingResult result) throws Exception{
        if(result.hasErrors()){//判断是否有验证失败信息
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            String str = om.writeValueAsString(errorList);
            return str;
        }

        System.out.println("执行业务方法");
        return "ok";
    }

     @RequestMapping("update")
    public String update(@Validated(ValidateUpdate.class)UserBean user,
                         BindingResult result) throws  Exception{
        if(result.hasErrors()){
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            return om.writeValueAsString(errorList);
        }
        System.out.println("执行修改业务");
        return "ok";
    }
}
